<?php


namespace app\model\hotel;


use app\model\BaseModel;
use app\model\pay\Huifu;
use app\model\system\Config;
use app\model\system\Cron;
use app\model\system\Group;
use Carbon\Carbon;
use think\facade\Cache;
use think\facade\Db;

/**
 * 酒店管理
 */
class Hotel extends BaseModel
{



    /**
     * 添加酒店
     * @param unknown $data
     */
    public function addHotel($data, $user_data = [])
    {
        $data[ 'create_time' ] = time();
        $data['username'] = $user_data[ 'username' ];
        model('hotel')->startTrans();

        try {
            $data[ 'hotel_id' ] = model("site")->add([ 'site_type' => 'hotel' ]);
            $hotel_id = model('hotel')->add($data);
            if ($data['direct']==1){
                //自营同步房间和房间类型
                $baoyu_model = new Baoyu();
                $room = $baoyu_model->roomList();
                $room_list = $room['data']['data']['rooms'];

                foreach ($room_list as $k=>$v){
                    if ($v['state']=='S'){
                        $room_data = [
                            'baoyu_id'=>$v['id'],
                            'roomNo'=>$v['roomNo'],
                            'state'=>$v['state'],
                            'type_id'=>$v['typeId'],
                            'type_name'=>$v['typeName'],
                            'create_time'=>strtotime($v['createTime']),
                            'modify_time'=>strtotime($v['lastmodifyTime']),
                            'hotel_id'=>$hotel_id,
                        ];
                        model("hotel_room_no")->add($room_data);
                    }
                }

                $room_type = $baoyu_model->roomTypeList();
                $room_list = $room_type['data']['data']['roomTypes'];

                foreach ($room_list as $k=>$v){
                    $room_data = [
                        'baoyu_type_id'=>$v['id'],
                        'type_name'=>$v['name'],
                        'companyId'=>$v['companyId'],
                        'create_time'=>strtotime($v['createTime']),
                        'hotel_id'=>$hotel_id,
                    ];
                    model("hotel_room_type")->add($room_data);
                }
            }


            Cache::tag("hotel")->clear();
            //添加系统用户组
            $group = new Group();
            $group_data = [
                'site_id' => $hotel_id,
                'app_module' => 'hotel',
                'group_name' => '管理员组',
                'is_system' => 1,
                'create_time' => time()
            ];
            $group_id = $group->addGroup($group_data)[ 'data' ];

            //用户检测
            if (empty($user_data[ 'username' ])) {
                model("hotel")->rollback();
                return $this->error('', 'USER_NOT_EXIST');
            }
            $user_count = model("user")->getCount([ [ 'username', '=', $user_data[ 'username' ] ], [ 'app_module', '=', 'hotel' ] ]);
            if ($user_count > 0) {
                model("hotel")->rollback();
                return $this->error('', 'USERNAME_EXISTED');
            }

            //添加用户
            $data_user = [
                'app_module' => 'hotel',
                'app_group' => 0,
                'is_admin' => 1,
                'group_id' => $group_id,
                'group_name' => '管理员组',
                'site_id' => $hotel_id
            ];
            $user_info = array_merge($data_user, $user_data);
            model("user")->add($user_info);

            Cache::tag("hotel")->clear();

            model('hotel')->commit();
            return $this->success($hotel_id);
        } catch (\Exception $e) {

            model('hotel')->rollback();
            return $this->error('', $e->getMessage());
        }

    }

    /**
     * 修改酒店
     * @param unknown $data
     * @return multitype:string
     */
    public function editHotel($data, $condition)
    {
        $data[ "modify_time" ] = time();
        $res = model('hotel')->update($data, $condition);
        Cache::tag("hotel")->clear();
        return $this->success($res);
    }

    /**
     * 删除酒店
     * @param $condition
     * @return array
     */
    public function deleteHotel($condition)
    {
        $hotel_id = isset($check_condition[ 'hotel_id' ]) ? $check_condition[ 'hotel_id' ] : '';
        if ($hotel_id === '') {
            return $this->error('', '缺少参数酒店id');
        }
        model('hotel')->startTrans();
        try {
            //删除站点
            model('site')->delete([ [ 'app_module', '=', 'hotel' ], [ 'site_id', '=', $hotel_id ] ]);
            //删除酒店
            model('hotel')->delete($condition);
            Cache::tag("hotel")->clear();
            //删除用户组
            model('group')->delete([ [ 'app_module', '=', 'hotel' ], [ 'site_id', '=', $hotel_id ] ]);
            //删除用户
            model('user')->delete([ [ 'app_module', '=', 'hotel' ], [ 'site_id', '=', $hotel_id ] ]);

            event("DeleteHotel", [ 'hotel_id' => $hotel_id ]);

            model('hotel')->commit();
            return $this->success();

        } catch (\Exception $e) {

            model('hotel')->rollback();
            return $this->error('', $e->getMessage());
        }
    }

    /**
     * @param $condition
     * @param $is_frozen
     */
    public function frozenHotel($condition, $is_frozen)
    {
        $res = model('hotel')->update([ 'is_frozen' => $is_frozen ], $condition);
        Cache::tag("hotel")->clear();
        return $this->success($res);
    }

    public function statusHotel($condition, $is_frozen)
    {
        $res = model('hotel')->update([ 'status' => $is_frozen ], $condition);
        Cache::tag("hotel")->clear();
        return $this->success($res);
    }

    /**
     * 获取酒店信息
     * @param array $condition
     * @param string $field
     */
    public function getHotelInfo($condition, $field = '*')
    {
       /* $data = json_encode([ $condition, $field ]);
        $cache = Cache::get("hotel_" . $data);
        if (!empty($cache)) {
            return $this->success($cache);
        }*/
        $res = model('hotel')->getInfo($condition, $field);
        //Cache::tag("hotel")->set("hotel_" . $data, $res);
        return $this->success($res);
    }

    /**
     * 获取酒店列表
     * @param array $condition
     * @param string $field
     * @param string $order
     * @param string $limit
     */
    public function getHotelList($condition = [], $field = '*', $order = '', $limit = null)
    {
        $data = json_encode([ $condition, $field, $order, $limit ]);
        $cache = Cache::get("hotel_getHotelList_" . $data);
        if (!empty($cache)) {
            return $this->success($cache);
        }
        $list = model('hotel')->getList($condition, $field, $order, '', '', '', $limit);
        Cache::tag("hotel")->set("hotel_getHotelList_" . $data, $list);

        return $this->success($list);
    }

    /**
     * 获取酒店分页列表
     * @param array $condition
     * @param number $page
     * @param string $page_size
     * @param string $order
     * @param string $field
     */
    public function getHotelPageList($condition = [], $page = 1, $page_size = PAGE_LIST_ROWS, $order = '', $field = '*')
    {
        $data = json_encode([ $condition, $field, $order, $page, $page_size ]);
        $cache = Cache::get("hotel_getHotelPageList_" . $data);
        if (!empty($cache)) {
            return $this->success($cache);
        }
        $list = model('hotel')->pageList($condition, $field, $order, $page, $page_size);
        Cache::tag("hotel")->set("hotel_getHotelPageList_" . $data, $list);
        return $this->success($list);
    }

    /**
     * 查询酒店  带有距离
     * @param $condition
     * @param $lnglat
     */
    public function getLocationHotelList($condition, $field, $lnglat)
    {
        $order = '';
        if ($lnglat[ 'lat' ] !== null && $lnglat[ 'lng' ] !== null) {
            $field .= ' , FORMAT(st_distance ( point ( ' . $lnglat[ 'lng' ] . ', ' . $lnglat[ 'lat' ] . ' ), point ( longitude, latitude ) ) * 111195 / 1000, 2) as distance ';
            $condition[] = [ '', 'exp', Db::raw(' FORMAT(st_distance ( point ( ' . $lnglat[ 'lng' ] . ', ' . $lnglat[ 'lat' ] . ' ), point ( longitude, latitude ) ) * 111195 / 1000, 2) < 10000') ];
            $order = 'distance asc';
        }

        $list = model('hotel')->getList($condition, $field, $order);
        return $this->success($list);
    }

    /**
     * 查询酒店  带有距离
     * @param $condition
     * @param $lnglat
     */
    public function getLocationHotelPageList($condition, $page = 1, $page_size = PAGE_LIST_ROWS, $field, $lnglat)
    {
        $order = '';
        if ($lnglat[ 'lat' ] !== null && $lnglat[ 'lng' ] !== null) {
            $field .= ',FORMAT(st_distance ( point ( ' . $lnglat[ 'lng' ] . ', ' . $lnglat[ 'lat' ] . ' ), point ( longitude, latitude ) ) * 111195 / 1000, 2) as distance';
            $condition[] = [ '', 'exp', Db::raw(' FORMAT(st_distance ( point ( ' . $lnglat[ 'lng' ] . ', ' . $lnglat[ 'lat' ] . ' ), point ( longitude, latitude ) ) * 111195 / 1000, 2) < 10000') ];
            $order = Db::raw(' st_distance ( point ( ' . $lnglat[ 'lng' ] . ', ' . $lnglat[ 'lat' ] . ' ), point ( longitude, latitude ) ) * 111195 / 1000 asc');
        }
        $list = model('hotel')->pageList($condition, $field, $order, $page, $page_size);
        return $this->success($list);
    }

    /**
     * 删除酒店（事件）
     * @param $hotel_id
     * @return array
     */
    public function cronDeleteHotel($hotel_id)
    {
        model('hotel_room')->startTrans();
        try {

            //删除酒店商品
            model('hotel_room')->delete([ [ 'hotel_id', '=', $hotel_id ] ]);
            //删除用户日志
            model('user_log')->delete([ [ 'site_id', '=', $hotel_id ] ]);

            model('hotel_room')->commit();
            return $this->success();
        } catch (\Exception $e) {

            model('hotel_room')->rollback();
            return $this->error('', $e->getMessage());
        }
    }


    public function idCardType()
    {
        $data = [
            '居民身份证‌','‌临时身份证‌','军官证','武警警官证','士兵证','‌护照','‌港澳居民来往内地通行证','台湾居民来往大陆通行证‌','外国人居留证','外国人出入境证‌'
        ];

        return $data;
    }


    public function applyPass($hotel_id,$data,$user_info)
    {
        model('hotel')->startTrans();

        try {
            $data[ 'hotel_id' ] = model("site")->add([ 'site_type' => 'hotel' ]);

            if ($data['direct']==1){
                //自营同步房间和房间类型
                $baoyu_model = new Baoyu();
                $room = $baoyu_model->roomList();
                $room_list = $room['data']['data']['rooms'];

                foreach ($room_list as $k=>$v){
                    if ($v['state']=='S'){
                        $room_data = [
                            'baoyu_id'=>$v['id'],
                            'roomNo'=>$v['roomNo'],
                            'state'=>$v['state'],
                            'type_id'=>$v['typeId'],
                            'type_name'=>$v['typeName'],
                            'create_time'=>strtotime($v['createTime']),
                            'modify_time'=>strtotime($v['lastmodifyTime']),
                            'hotel_id'=>$hotel_id,
                        ];
                        model("hotel_room_no")->add($room_data);
                    }
                }

                $room_type = $baoyu_model->roomTypeList();
                $room_list = $room_type['data']['data']['roomTypes'];

                foreach ($room_list as $k=>$v){
                    $room_data = [
                        'baoyu_type_id'=>$v['id'],
                        'type_name'=>$v['name'],
                        'companyId'=>$v['companyId'],
                        'create_time'=>strtotime($v['createTime']),
                        'hotel_id'=>$hotel_id,
                    ];
                    model("hotel_room_type")->add($room_data);
                }
            }

            //添加系统用户组
            $group = new Group();
            $group_data = [
                'site_id' => $hotel_id,
                'app_module' => 'hotel',
                'group_name' => '管理员组',
                'is_system' => 1,
                'create_time' => time()
            ];
            $group_id = $group->addGroup($group_data)[ 'data' ];

            //用户检测
            if (empty($user_data[ 'username' ])) {
                model("hotel")->rollback();
                return $this->error('', 'USER_NOT_EXIST');
            }
            $user_count = model("user")->getCount([ [ 'username', '=', $user_data[ 'username' ] ], [ 'app_module', '=', 'hotel' ] ]);
            if ($user_count > 0) {
                model("hotel")->rollback();
                return $this->error('', 'USERNAME_EXISTED');
            }

            //添加用户
            $data_user = [
                'app_module' => 'hotel',
                'app_group' => 0,
                'is_admin' => 1,
                'group_id' => $group_id,
                'group_name' => '管理员组',
                'site_id' => $hotel_id
            ];
            $user_info = array_merge($data_user, $user_data);
            model("user")->add($user_info);

            $res = model('hotel')->update($data, [ [ 'hotel_id', '=', $hotel_id ] ]);

            model("hotel")->commit();
            return $this->success($res);
        } catch (\Exception $e) {
            model("hotel")->rollback();
            return $this->error("", $e->getMessage());
        }
    }

    //提交汇付
    public function submitHuifu($condition)
    {
        model('hotel')->startTrans();

        try {
            $return_url = addon_url("pay/huifu/hotelnotify");

            $info = model('hotel')->getInfo($condition);

            $huifu_model = new Huifu();
            $req_seq_id = date("YmdHis");

            if ($info['hotel_type']==1){
                $legal_cert_back_pic_url = root_path() .$info['front_pic_id_card'];
                $legal_cert_back_pic = $huifu_model->upload('F41', $legal_cert_back_pic_url,'身份证正面.png');
                $legal_cert_back_pic_file_id = $legal_cert_back_pic['data']['file_id'];

                $legal_cert_front_pic_url = root_path() .$info['reverse_pic_id_card'];
                $legal_cert_front_pic = $huifu_model->upload('F40',$legal_cert_front_pic_url,'身份证反面.png');
                $legal_cert_front_pic_file_id = $legal_cert_front_pic['data']['file_id'];

                $settle_card_front_pic_url = root_path() .$info['bank_img'];
                $settle_card_front_pic = $huifu_model->upload('F13',$settle_card_front_pic_url,'银行卡.png');
                $settle_card_front_pic_file_id = $settle_card_front_pic['data']['file_id'];

                $card_info = [
                    'card_name'=>$info['bank_name'],
                    'card_no'=>$info['bank_number'],
                    //'area_id'=>'310100',
                    'cert_type'=>'00',
                    'cert_no'=>$info['id_card_number'],
                    'cert_validity_type'=>$info['legal_cert_validity_type'],
                    'cert_begin_date'=>date('Ymd',strtotime($info['id_card_start_time'])),
                    'cert_end_date'=>date('Ymd',strtotime($info['id_card_end_time']))
                ];
                //个人店铺
                $data = [
                    'req_seq_id'=>$req_seq_id,
                    'reg_name'=>$info['hotel_name'],
                    'prov_id'=>$info['province_id'],
                    'area_id'=>$info['city_id'],
                    'district_id'=>$info['district_id'],
                    'detail_addr'=>$info['full_address'].$info['address'],
                    'contact_name'=>$info['name'],
                    'contact_mobile_no'=>$info['telphone'],
                    'contact_email'=>$info['contact_email'],
                    'return_url'=>$return_url,
                    'mcc'=>'5399',
                    'scene_type'=>'ALL',
                    'legal_cert_no'=>$info['id_card_number'],
                    'legal_cert_begin_date'=>$info['id_card_start_time'],
                    'legal_cert_end_date'=>$info['id_card_end_time'],
                    'legal_addr'=>$info['legal_addr'],
                    'legal_cert_back_pic'=>$legal_cert_back_pic_file_id,
                    'legal_cert_front_pic'=>$legal_cert_front_pic_file_id,
                    'settle_card_front_pic'=>$settle_card_front_pic_file_id,
                    'card_info'=>json_encode($card_info,320)
                ];

                $result = $huifu_model->personalMerchantPurchase($data);

            } else {

                $license_pic_url = root_path() .$info['business_license'];
                $license_pic = $huifu_model->upload('F07', $license_pic_url,'营业执照.png');
                $license_pic_file_id = $license_pic['data']['file_id'];

                //银行卡类型,1对公,2对私,3对私非法人
                if ($info['bank_type']==1){
                    $card_type = 0;
                } elseif ($info['bank_type']==2){
                    $card_type = 1;
                } elseif ($info['bank_type']==3){
                    $card_type = 2;
                }
                $card_info = [
                    'card_name'=>$info['bank_name'],
                    'card_no'=>$info['bank_number'],
                    'cert_type'=>'00',
                    'card_type'=>$card_type,//0：对公账户 1：对私法人账户 2：对私非法人账户
                ];
                if ($card_type==0){
                    $card_info['prov_id'] = $info['bank_province'];
                    $card_info['area_id'] = $info['bank_city'];
                }
                //企业
                $data = [
                    'req_seq_id'=>$req_seq_id,
                    'reg_name'=>$info['hotel_name'],
                    'short_name'=>$info['hotel_name'],
                    'ent_type'=>0,
                    'license_pic'=>$license_pic_file_id,
                    'license_code'=>$info['business_license_number'],
                    'license_validity_type'=>$info['business_license_type'],
                    'license_begin_date'=>$info['business_license_start_time'],
                    'license_end_date'=>$info['business_license_end_time'],
                    'reg_prov_id'=>$info['province_id'],
                    'reg_area_id'=>$info['city_id'],
                    'reg_district_id'=>$info['district_id'],
                    'reg_detail'=>$info['full_address'].$info['address'],
                    'legal_name'=>$info['id_card_name'],
                    'legal_cert_type'=>'00',
                    'legal_cert_no'=>$info['id_card_number'],
                    'legal_cert_validity_type'=>$info['legal_cert_validity_type'],
                    'legal_cert_begin_date'=>$info['id_card_start_time'],
                    'legal_cert_end_date'=>$info['id_card_end_time'],
                    'legal_addr'=>$info['legal_addr'],
                    'prov_id'=>$info['province_id'],
                    'area_id'=>$info['city_id'],
                    'district_id'=>$info['district_id'],
                    'detail_addr'=>$info['full_address'].$info['address'],
                    'contact_mobile_no'=>$info['telphone'],
                    'mcc'=>'5399',
                    'scene_type'=>'ALL',
                    'receipt_name'=>$info['hotel_name'],
                    'contact_email'=>$info['contact_email'],
                    'busi_type'=>$info['busi_type'],
                    'return_url'=>$return_url,
                    'card_info'=>json_encode($card_info,320)
                ];
                //dump($data);die;
                $result = $huifu_model->businessMerchantPurchase($data);
            }

            if ($result[ "code" ] < 0)
                return $result;

            $update_data = [
                'req_seq_id'=>$req_seq_id,
                'huifu_audit_status'=>1,
                'huifu_id'=>$result['data']['huifu_id'],
                'huifu_apply_no'=>$result['data']['apply_no'] ?? '',
                'huifu_resp_desc'=>$result['data']['resp_desc'] ?? '',
                'huifu_token_no'=>$result['data']['token_no'] ?? '',
            ];

            $res = model('hotel')->update($update_data,$condition);

            model('hotel')->commit();

            return $this->success($res);

        }  catch (\Exception $e) {
            model('hotel')->rollback();
            return $this->error('', $e->getMessage());
        }

    }
}